<?php

namespace App\Tasks;

use App\Clients\JinShouFu\DownloadFile;
use App\Clients\JinShouFu\ExportRecordPage;
use App\Clients\JinShouFu\PayReportBatchAddTask;
use App\Excels\Imports\JinShouFuSubAccountImport;
use App\Models\Account;
use App\Models\AccountMapping;
use App\Models\JinshoufuSubAccountTask;
use App\Models\Mall;
use App\Models\MallDateFinance;
use GuzzleHttp\Exception\GuzzleException;
use Maatwebsite\Excel\Facades\Excel;

class JinShouFuSubAccountSyncTask
{

    protected Account $account;

    protected Mall $mall;

    public function __construct(Account $account)
    {
        $this->account = $account;
    }

    /**
     * @throws GuzzleException
     */
    public function execute(): void
    {
        $this->applyForFile();
        sleep(10);
        $this->queryForFile();
        sleep(10);
        //exit();
        $this->updateMallDateSettleMoney();
    }


    /**
     * @throws GuzzleException
     */
    public function updateMallDateSettleMoney(): void
    {
        $pageItems = JinshoufuSubAccountTask::query()
            ->where("status",2)
            //->where("id",230)
            ->get();
        $baseDir = storage_path("app/public/jinshou_excel");
        !is_dir($baseDir) and mkdir(storage_path("app/public/jinshou_excel"),0777);
        $client = new DownloadFile($this->account);
        foreach ($pageItems as $pageItem){
            $id = parse_url($pageItem->file_url);
            $id = $id["query"];
            $id = explode("=",$id);
            $id = $id[1];
            $fileName = $baseDir."/".$pageItem->id.".xlsx";
            $client->filePath = $fileName;
            $client->loopExecute(["id"=>$id])->contents();
            //$fileName = "/www/wwwroot/Finance/storage/app/public/jinshou_excel/234.xlsx";
            $importer = new JinShouFuSubAccountImport;
            Excel::import($importer, $fileName);
            $merchantNos = AccountMapping::query()
                ->where("mall_type",2)
                ->pluck("merchant_no")
                ->toArray();
            if(empty($importer->datas["datas"])){
                $date = date("Y-m-d",strtotime($pageItem->begin_date) - 86400);
                MallDateFinance::query()
                    ->whereIn("merchant_no",$merchantNos)
                    ->where("date",$date)
                    ->update([
                        "settle_money"=>0
                    ]);
                $pageItem->status = 4;
                $pageItem->save();
                continue;
            }
            $merchantNames = [];
            foreach ($importer->datas["datas"] as $data){
                empty($merchantNames[$data["merchantName"]]) and $merchantNames[$data["merchantName"]] = [
                    "merchantName"=>$data["merchantName"],
                    "settleMoney"=>0,
                ];
                if($data["merchantName"] == "禅逸瑜伽（璞誉店）"){
                    $rate = 0.5;
                }else{
                    $rate = 0.08;
                }
                $merchantNames[$data["merchantName"]]["settleMoney"] += $data["payment"] * $rate;
            }
            $merchants = Mall::query()->whereIn("name",array_keys($merchantNames))->get();
            foreach ($merchantNames as $merchantName){
                $merchant = $merchants->where("name",$merchantName["merchantName"])->first();
                if(empty($merchant)){
                    continue;
                }
                $finance = MallDateFinance::query()
                    ->where("merchant_no",$merchant->merchant_no)
                    ->where("date",$importer->datas["date"])
                    ->first();
                if(empty($finance)) continue;
                $finance->settle_money = round($merchantName["settleMoney"],2);
                $finance->save();
            }
            $pageItem->status = 4;
            $pageItem->save();
        }
    }

    /**
     * @throws GuzzleException
     */
    public function queryForFile(): void
    {
        $pageItems = JinshoufuSubAccountTask::query()
            ->where("status",1)
            ->where("times","<=",10)
            ->get();
        $client = new ExportRecordPage($this->account);
        foreach ($pageItems as $pageItem){
            $queryData = [
                "fileName"=>$pageItem->begin_date."至".$pageItem->end_date,
                "startTime"=>date("Y-m-d",time() - 86400 * 10),
                "endTime"=>date("Y-m-d",time()),
            ];
            $response = $client->loopExecute($queryData)->contents();
//            var_dump($response);
//            exit();
            if(empty($response) || empty($response[0]["fileUrl"])){
                if($pageItem->times >= 10){
                    $pageItem->status = 3;
                }else{
                    $pageItem->times += 1;
                }
                $pageItem->save();
                continue;
            }
            $pageItem->file_url = $response[0]["fileUrl"];
            $pageItem->status = 2;
            $pageItem->save();
        }

    }

    /**
     * @throws GuzzleException
     */
    public function applyForFile(): void
    {
        $pageItems = JinshoufuSubAccountTask::query()
            ->where("status",0)
            ->get();
        $client = new PayReportBatchAddTask($this->account);
        foreach ($pageItems as $pageItem){
            $postData = [
                "beginTime"=>$pageItem->begin_date,
                "endTime"=>$pageItem->end_date,
            ];
            $response = $client->loopExecute($postData)->contents();
            if(!$response) continue;
            $pageItem->status = 1;
            $pageItem->save();
        }
    }


}
